<template>
    <div class="edit-drawer">
        <drawer ref="drawerRef" :title="drawerTitle" :async="true" width="550px" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <el-form-item label="字典类型" prop="type">
                    <el-autocomplete v-model="formData.type" :fetch-suggestions="querySearch"
                        placeholder="请输入字典类型"></el-autocomplete>
                </el-form-item>
                <el-form-item label="字典值" prop="value">
                    <el-input v-model="formData.value" placeholder="请输入字典值"></el-input>
                </el-form-item>
            </el-form>
        </drawer>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { dictTypes, dictEdit, dictAdd, dictDetail } from '@/api/common/dict'
import Drawer from '@/components/drawer/index.vue'
import { useDictOptions } from '@/hooks/useDictOptions'
import feedback from '@/utils/feedback'
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const drawerRef = shallowRef<InstanceType<typeof Drawer>>()
const mode = ref('add')
const drawerTitle = computed(() => {
    return mode.value == 'edit' ? '编辑字典' : '新增字典'
})
const formData = reactive({
    id: '',
    type: '',
    value: '',
    status: true
})

const formRules = {

}

const querySearch = (query: string) => {
    return optionsData.dict.filter((item) => item.label.includes(query))
}

const { optionsData } = useDictOptions<{
    dict: any[]
}>({
    dict: {
        api: dictTypes
    }
})

const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit' ? await dictEdit(formData) : await dictAdd(formData)
    drawerRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    if (type == 'add'){
        formRef.value?.resetFields()
    }
    drawerRef.value?.open()
}

const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore          
            formData[key] = data[key]
        }
        //TODO：因为后端返回字段为is_stop
        else {
            //@ts-ignore  
            formData[key] = data['is_stop']
        }
    }

}

const getDetail = async (row: Record<string, any>) => {
    const data = await dictDetail({
        id: row.id
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
